package com.baidu.sggc.controller;

import com.baidu.sggc.audit.extend.AuditExtendContext;
import com.baidu.sggc.audit.extend.GeneralMessage;
import com.baidu.sggc.core.annotation.AuditLog;
import com.baidu.sggc.core.common.R;
import com.baidu.sggc.data.req.AppInstanceListReq;
import com.baidu.sggc.data.req.ProductCreateReq;
import com.baidu.sggc.data.req.ProductListReq;
import com.baidu.sggc.data.req.ProductUpdateReq;
import com.baidu.sggc.data.resp.Page;
import com.baidu.sggc.entity.ProductInfo;
import com.baidu.sggc.entity.UserContext;
import com.baidu.sggc.mapper.ProductInfoMapper;
import com.baidu.sggc.service.ProductInfoService;
import com.baidu.sggc.entity.vo.ProductInfoVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/product")
@Tag(name = "ProductInfoController", description = "产品信息控制器")
public class ProductInfoController {

  @Autowired
  private ProductInfoService productInfoService;

  @Autowired
  private ProductInfoMapper productInfoMapper;

  @Operation(summary = "根据筛选条件获取产品列表")
  @PostMapping("/list")
  @ResponseBody
  @AuditLog(module = "产品管理", auditObject = "产品", operation = "listQuery", message = "查询产品列表")
  public R<Page<ProductInfoVo>> list(@RequestBody ProductListReq req) {
    req.validate();

    Map<String, Map<String, String>> extendData = new LinkedHashMap<String, Map<String, String>>();
    Map<String, String> condition = new LinkedHashMap<String, String>();
    condition.put("产品名称", req.getKeyWord());
    condition.put("产品类型", req.getCreateTypeFilter());
    extendData.put("查询条件", condition);
    AuditExtendContext.setExtendData((Map) extendData);

    return R.ok(productInfoService.getProductInfoList(req));
  }

  @Operation(summary = "根据id获取产品信息")
  @GetMapping("/get")
  @ResponseBody
  @AuditLog(module = "产品管理", auditObject = "产品", operation = "detailsQuery", message = "获取产品信息")
  public R<ProductInfoVo> get(Long id) {
    if (id == null) {
      throw new IllegalArgumentException("id cannot be null");
    }

    GeneralMessage msg = new GeneralMessage();
    msg.setDataType("产品");
    msg.setDataName("产品ID:" + id);
    msg.setUniqueIdentification(Collections.singletonList(String.valueOf(id)));
    msg.setOperationNum(1);
    AuditExtendContext.setExtendData(toMap(msg));

    return R.ok(productInfoService.getProductInfoById(id));
  }

  @Operation(summary = "根据产品id编辑产品")
  @PostMapping("/update")
  @ResponseBody
  @AuditLog(module = "产品管理", auditObject = "产品", operation = "update", message = "更新产品信息")
  public R<Boolean> update(@RequestBody ProductUpdateReq req) {
    req.validate();

    GeneralMessage msg = new GeneralMessage();
    msg.setDataType("产品");
    msg.setDataName(req.getProductName());
    msg.setUniqueIdentification(Collections.singletonList(String.valueOf(req.getId())));
    msg.setOperationNum(1);
    AuditExtendContext.setExtendData(toMap(msg));

    return R.ok(productInfoService.updateProductInfoById(req));
  }

  @Operation(summary = "创建产品时远程查询所有应用列表")
  @PostMapping("/queryAppInstanceList")
  @ResponseBody
  @AuditLog(module = "产品管理", auditObject = "应用实例", operation = "listQuery", message = "查询应用实例列表")
  public R<List<ProductInfoVo>> queryAppInstanceList(@RequestBody AppInstanceListReq req) {
    req.validate();
    return R.ok(productInfoService.getAppInstanceList(req));
  }

  @Operation(summary = "创建产品")
  @PostMapping("/add")
  @ResponseBody
  @AuditLog(module = "产品管理", auditObject = "产品", operation = "create", message = "创建产品")
  public R<Boolean> add(@RequestBody ProductCreateReq req) {
    req.validate();

    // 插入并回填 ID
    ProductInfo productInfo = new ProductInfo();
    BeanUtils.copyProperties(req, productInfo);
    String userId = UserContext.getUserId();
    String userName = UserContext.getUserName();
    if (userId != null) {
      productInfo.setCreateId(userId);
    }
    if (userName != null) {
      productInfo.setCreateName(userName);
    }
    productInfoMapper.insert(productInfo); // 这里会回填主键

    // 设置审计扩展字段
    GeneralMessage msg = new GeneralMessage();
    msg.setDataType("产品");
    msg.setDataName(productInfo.getProductName());
    msg.setUniqueIdentification(Collections.singletonList(String.valueOf(productInfo.getProductId()))); // 用回填后的 ID
    msg.setOperationNum(1);
    AuditExtendContext.setExtendData(toMap(msg));

    return R.ok(true);
  }

  @Operation(summary = "根据产品id删除产品")
  @PostMapping("/del")
  @ResponseBody
  @AuditLog(module = "产品管理", auditObject = "产品", operation = "delete", message = "删除产品")
  public R<Boolean> del(@RequestBody ProductInfo req) {
    if (req.getId() == null) {
      throw new IllegalArgumentException("id cannot be null");
    }

    GeneralMessage msg = new GeneralMessage();
    msg.setDataType("产品");
    msg.setDataName(req.getProductName());
    msg.setUniqueIdentification(Collections.singletonList(String.valueOf(req.getId())));
    msg.setOperationNum(1);
    AuditExtendContext.setExtendData(toMap(msg));

    return R.ok(productInfoService.deleteProductInfoById(req));
  }

  private Map<String, Object> toMap(Object obj) {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.convertValue(obj, Map.class);
  }
}
